prompt ;

lim = -99.9

cd ~/xds
addpath ~/xds/fun

opt = {"UniformOutput", false} ;
sep = ";" ;
fmt = ["%d %s %s" repmat(" %f", 1, 9)] ; pfx = "data/Ceara/" ;

V = {"P" "Tx" "Tn" "S" "E" "T" "H" "W"} ;

lat = lon = alt = [] ; ids = vars = {} ;
for v = V
    eval([v{:} " = [] ;"]) ;
endfor
for f = glob([pfx "*.txt"])'

   printf("ceara: <-- %s\n", f = f{:}) ;
   [fd ff fs] = fileparts(f) ;

   fid = fopen(f) ; C = cellfun(@(x) fgetl(fid), cell(1,7), "UniformOutput", false) ; fclose(fid) ;
   ids = union(ids, ff) ;
   lat = [lat str2num(C{5}(20:end))] ;
   lon = [lon str2num(C{6}(20:end))] ;
   alt = [alt str2num(C{7}(20:end))] ;

   C = textscan(fid = fopen(f), fmt, "delimiter", sep, "headerlines", 16) ; fclose(fid) ;

   idn = C{1} ;
   id_1 = C{2} ;
   id_2 = C{3} ;
   id = cellfun(@(d,h) datevec([d h], "dd/mm/yyyyHHMM"), id_1, id_2, opt{:}) ;
   id = cell2mat(id) ;

   j = 3 ;
   for v = V
      v = v{:} ;
      eval(["s" v ".id = id ;"]) ;
      eval(["s" v ".x = C{" num2str(++j) "} ;"]) ;
      eval(["[s" v ".id s" v ".x] = dayavg(s" v ".id, s" v ".x) ;"]) ;
      eval([v " = join(" v ", s" v ") ;"]) ;
   endfor

endfor

C = {} ;
pdd = [] ; i = 1 ;
C(i,:) = {"id" "var" "name" "lon" "lat" "alt" "undef"} ;
for v = V
   v = v{:} ;

   for j=1:length(ids)
      C(++i,:) = {ids{j} v, v, lon(j), lat(j), alt(j), lim} ;
   endfor

   eval([v ".vars = repmat({\"" v "\"}, 1, length(ids));"]) ;
   eval([v ".ids = ids ;"]) ;
   eval([v ".lon = lon ;"]) ;
   eval([v ".lat = lat ;"]) ;
   eval([v ".alt = alt ;"]) ;
   eval(["pdd = join(pdd, " v ") ;"]) ;

endfor

pdd.x = nan2lim(pdd.x) ;

cell2csv([pfx, "pdd/meta.txt"], C)
out(V, [pfx "pdd"], pdd) ;


function out (V, odir, s)

   ## usage: out (V, odir, s)
   ## 
   ## output s

   for v = V

      v = v{:} ;
      J = strcmp(s.vars, v) ;

      fid = fopen(ofile = fullfile(odir, [v ".csv"]), "wt") ;
      fmt = ["Y,M,D" repmat(",%s", 1, sum(J)) "\n"] ;
      fprintf(fid, fmt, s.ids(:,J){:}) ;
      fmt = ["%d,%d,%d" repmat(",%.4g", 1, sum(J)) "\n"] ;
      fprintf(fid, fmt, [s.id(:,1:3) s.x(:,J)]') ;
      fclose(fid) ;

      # csvwrite(ofile = [opfx v ".csv"], [s.id(:,1:3) s.x(:,J)], "precision", PAR.precision) ;
      printf("out: --> %s\n", ofile) ;

   endfor
	 
endfunction
